package com.keur.money.ui.steps.fm

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.config.KeurConfigs
import com.keur.money.databinding.FmMullaStepAccountBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpFm
import com.keur.money.ui.steps.act.KeurStepsAct
import com.keur.money.ui.steps.adapter.KeurStepAccountAdapter
import com.keur.money.ui.steps.impl.KeurStepAccountPresenterImpl
import com.keur.money.ui.steps.view.IKeurStepAccountView
import com.keur.money.utils.dialog.BindCardAddDialog
import com.keur.money.utils.dialog.BindCardDeleteDialog
import com.keur.money.utils.dialog.BindCardOtherDialog
import com.keur.money.utils.dialog.BindCardSubmitDialog
import com.keur.money.utils.dialog.BindCardSubmitWarningDialog
import com.keur.money.utils.event.KeurBehaviorTracker
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class KeurStepAccountFm(): MvpFm<IKeurStepAccountView, KeurStepAccountPresenterImpl>(),IKeurStepAccountView {
    private var _binding: FmMullaStepAccountBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var stepTitle = ""

    private var accountAdapter: KeurStepAccountAdapter? = null

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun createPresenter(): KeurStepAccountPresenterImpl {
        return KeurStepAccountPresenterImpl(context)
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaStepAccountBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        stepItem?.let {
            _binding?.textStepTitle?.text = it.optString("showTitle")
        }
        initMullaRecyclerViews()

        //积分
        _binding?.textPoints?.text = String.format(getString(R.string.step_phonebook_add_points),KeurCustomConfigsHelper.getMullaAddAccountPoints())
    }

    override fun initMullaListener() {
        //添加
        _binding?.addLayout?.setOnClickListener {
            showMullaBinCardAddDialog()
        }

        //提交
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            HttpHelper.addKeurEventAction(String.format(KeurEventType.CLICK.KEUR_CLICK_STEP_XX_NEXT, stepTitle),"")
            if (!isMullaSubmit()){
                showMullaErrorTipsDialog(getString(R.string.tips_submit_error), stepTitle)
                return@setOnClickListener
            }
            checkMullaSubmit()

//            val act = context as MullaStepsAct
//            act.onMullaSubmitProcessAction(stepItem.optString("apiUrl"),params)
//            HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_NEXT, stepTitle),"")
        }
    }

    override fun initMullaData() {
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_ACCOUNT_START)
        presenter.loadMullaAccountListAction()
    }

    /**
     * 初始化Views
     */
    private fun initMullaRecyclerViews(){
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerView?.layoutManager = layoutManager
        accountAdapter = KeurStepAccountAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = accountAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter?.getItem(position)
            when(childView.id){
                R.id.editLayout -> {//添加
                    showMullaBinCardAddDialog()
                }
                R.id.imgDelete -> {//删除
                    item?.let {
                        showMullaDeleteDialog(it)
                    }
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    override fun showMullaAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList

        accountAdapter?.let { adapter ->
            // TODO: 贝宁只能绑一个卡，绑卡成功之后直接提交刷新流程
            if (KeurConfigs.isBenin() && adapter.getAccountCount() > 0){
                context?.let {
                    val act = it as KeurStepsAct
                    act.showMullaSubmitSuccess()
                }
                return
            }
            
            //最多添加10个账户
            if (adapter.getAccountCount() >= 10){
                _binding?.addLayout?.isEnabled = false
                _binding?.addLayout?.setBackgroundResource(R.drawable.mulla_btn_disabled_12)
            } else {
                _binding?.addLayout?.isEnabled = true
                _binding?.addLayout?.setBackgroundResource(R.drawable.mulla_btn_pressed_12)
            }
        }
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showMullaBingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = BindCardOtherDialog(context,stepTitle,object : BindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnRight){//添加
                    presenter.submitMullaBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 添加绑卡dialog
     */
    private fun showMullaBinCardAddDialog(){
        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_USER_ACCOUNT_ADD,stepTitle)
        val bindCardDialog = BindCardAddDialog(context,stepTitle,object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter.submitMullaBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(true)
        bindCardDialog.show()
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showMullaSubmitWarningDialog(){
        val warningDialog = BindCardSubmitWarningDialog(context,stepTitle,object : BindCardSubmitWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btnNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        HttpHelper.addKeurEventAction(String.format(KeurEventType.CLICK.KEUR_CLICK_STEP_XX_NEXT, stepTitle),"")
                        val act = context as KeurStepsAct
                        act.showMullaSubmitSuccess()
                    }
                    R.id.btnAdd -> {//继续添加
                        showMullaBinCardAddDialog()
                    }
                }
            }
        })
        warningDialog.setCancelable(true)
        warningDialog.setCanceledOnTouchOutside(false)
        warningDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showMullaConfirmDialog(){
        accountAdapter?.data?.let {
            val submitDialog = BindCardSubmitDialog(context,object : BindCardSubmitDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnConfirm){
                        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                        // TODO: Step Next 批量埋点上报
                        KeurBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)

                        val act = context as KeurStepsAct
                        act.showMullaSubmitSuccess()
                    }
                }
            })
            submitDialog.show()
            submitDialog.setBindAccountList(it)
        }
    }

    /**
     * 删除提示
     */
    private fun showMullaDeleteDialog(item: JSONObject){
        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = BindCardDeleteDialog(context,stepTitle, object : BindCardDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnRight){
                    presenter.deleteMullaAccountAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(false)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isMullaSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        accountAdapter?.let {
            for (i in 0..<it.itemCount){
                //存在一个不是编辑状态的item，则可以提交
                if (!it.getItem(i).optBoolean("isEdit",true)){
                    submitIsEnabled = true
                    break
                }
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun checkMullaSubmit(){
        var count = 0
        accountAdapter?.let { adapter ->
            adapter.data.forEach {
                //不是编辑类型
                if (!it.optBoolean("isEdit",true)){
                    count += 1
                }
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showMullaSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showMullaConfirmDialog()
    }

    override fun onStart() {
        super.onStart()
        stepItem?.let {
            stepTitle = it.optString("stepTitle")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_ACCOUNT_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}